package de.fhdw.hbs.client.utils;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import de.fhdw.hbs.client.generated.HbsServiceException_Exception;
import de.fhdw.hbs.client.generated.LoginDTO;
import de.fhdw.hbs.client.gui.GUI;
import de.fhdw.hbs.client.ws.HbsClient;

/**
 * 
 * @author SZAHEL
 *
 */
public class Login extends JFrame implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	JButton SUBMIT;
	JPanel panel;
	JLabel label1, label2;
	final JTextField txtEmail, txtPasswort;
	LoginDTO login = new LoginDTO();
	private HbsClient wsClient = new HbsClient();

	public Login() {
		label1 = new JLabel();
		label1.setText("Email Adresse:");
		txtEmail = new JTextField(15);

		label2 = new JLabel();
		label2.setText("Passwort:");
		txtPasswort = new JPasswordField(15);

		SUBMIT = new JButton("Anmelden");

		panel = new JPanel(new GridLayout(3, 1));
		panel.add(label1);
		panel.add(txtEmail);
		panel.add(label2);
		panel.add(txtPasswort);
		panel.add(SUBMIT);
		add(panel, BorderLayout.CENTER);
		SUBMIT.addActionListener(this);
		setTitle("Anmeldung");
	}

	public void actionPerformed(ActionEvent ae) {
		try {
			login = doLogin();
			GUI window = new GUI(login);
			window.getFrame().setVisible(true);
			this.setVisible(false);
		} catch (Exception e) {
			System.out.println("Bitte Geben Sie korrekte Anmeldedaten ein!");
			JOptionPane.showMessageDialog(this, "Bitte geben Sie ihre korrekten Anmeldedaten an!",
					"Anmeldung fehlgeschlagen", JOptionPane.ERROR_MESSAGE);
			txtEmail.setText("");
			txtPasswort.setText("");
		}
	}

	private LoginDTO doLogin() {
		try {
			login = wsClient.loginByEmail(txtEmail.getText(), txtPasswort.getText());
		} catch (HbsServiceException_Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (login != null) {
			return login;
		}
		return null;
	}
}